import Vector2 from "../global/Vector2"
import TWEEN from '@tweenjs/tween.js'
import { getRandomArbitrary } from '../global/utils'

const point = document.querySelector('#point') as HTMLDivElement;

let width = document.body.offsetWidth
let height = document.body.offsetHeight
const onClick = (e: MouseEvent) => {
    const { clientX, clientY } = e

    const mouse = new Vector2(clientX, clientY)
    for (let i = 0; i < getRandomArbitrary(100, 1000); i++) {
        const end = mouse.clone()
            .setX(mouse.x + getRandomArbitrary(-width, width))
            .setY(mouse.y + getRandomArbitrary(-height, height))
        const div = createDiv(mouse)
        document.body.appendChild(div)
        changeFireworks(div, mouse, end, getRandomArbitrary(1, 2))
    }

}

const createDiv = (v: Vector2) => {
    const div: HTMLDivElement = document.createElement('div');
    div.classList.add('fieworks')
    div.style.background = randomColor().toString()
    div.style.left = v.x + 'px'
    div.style.top = v.y + 'px'
    return div
}
/**
 * 
 * @param element   移动的元素
 * @param s         起点坐标
 * @param e         终点坐标
 * @param time      执行时间
 */
const changeFireworks = (element: any, s: Vector2, e: Vector2, time = 1) => {
    new TWEEN.Tween(s)
        .to(e, time * 1000)
        .start()
        // .easing(TWEEN.Easing.Linear.None)
        .easing(TWEEN.Easing.Back.InOut) // 运动动画方式
        .onUpdate((v: any) => { // 更新时的回调
            const { x, y } = v
            element.style.left = x + 'px'
            element.style.top = y + 'px'
        })
        .onComplete(() => { // 结束的回调
            element.parentNode.removeChild(element)
        })
}

// 随机颜色
const randomColor = () => {
    const r = Math.floor(Math.random() * 255);
    const g = Math.floor(Math.random() * 255);
    const b = Math.floor(Math.random() * 255);
    return `rgb(${r},${g},${b})`

}
(function animate() {
    requestAnimationFrame(animate);
    TWEEN && TWEEN.update()
})()

const mouseMove = (e: MouseEvent) => {
    const { clientX, clientY } = e

    point.style.left = clientX - point.offsetWidth / 2 + 'px'
    point.style.top = clientY - point.offsetHeight / 2 + 'px'

}
window.addEventListener('click', onClick)
window.addEventListener('mousemove', mouseMove)


// for (let i = 0; i < 20; i++) {
//     const div = createDiv(mouse)
//     document.body.appendChild(div)
//     let y = getRandomArbitrary(5, 10), p1 = getRandomArbitrary(20, 60)
//     let i = 0
//     const interval = setInterval(() => {
//         if (i === y) clearInterval(interval)
//         let x1 = -Math.sqrt(2 * p1 * i)
//         const v1 = new Vector2(x1, i).add(mouse)
//         div.style.left = v1.x + 'px'
//         div.style.top = v1.y + 'px'
//         i++
//     }, 10)
// }
